
package com.jf.cloud.order.listener;

import cn.hutool.core.collection.CollUtil;
import com.jf.cloud.common.order.bo.OrderStatusBO;
import com.jf.cloud.common.constant.SendTypeEnum;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.bo.PayNotifyBO;
import com.jf.cloud.common.order.vo.SendNotifyBO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.common.util.Json;
import com.jf.cloud.order.model.Order;
import com.jf.cloud.order.service.OrderService;
import ma.glasnost.orika.MapperFacade;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 修改订单为待采购状态
 *
 * @author zz
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.SHOP_WALLET_NOTIFY_SERVICE_TOPIC, consumerGroup = RocketMqConstant.ORDER_NOTIFY_PURCHASE_GROUP)
public class OrderPurchaseConsumer implements RocketMQListener<PayNotifyBO> {

    private static final Logger LOG = LoggerFactory.getLogger(OrderPurchaseConsumer.class);


    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RocketMQTemplate sendOrderToPurchaseNotifyToShopTemplate;

    /**
     * 修改订单为待采购状态
     */
    @Override
    public void onMessage(PayNotifyBO message) {
        List<OrderStatusBO> orderStatusList = message.getOrderStatusList();
        if (CollUtil.isEmpty(orderStatusList)) {
            return;
        }
        LOG.info("订单支付成功，修改订单为待采购状态... message: " + Json.toJsonString(message));
        List<Order> orders = mapperFacade.mapAsList(orderStatusList, Order.class);
        // 修改订单的采购状态
        orderService.updateWaitPurchaseBatchById(orders);

        //推送订单待采购消息给店铺
        List<SendNotifyBO> notifyList = new ArrayList<>();
        for (OrderStatusBO order : orderStatusList) {
            SendNotifyBO sendNotifyBO = new SendNotifyBO();
            sendNotifyBO.setSendType(SendTypeEnum.TO_PURCHASE.getValue());
            sendNotifyBO.setBizId(order.getOrderId());
            notifyList.add(sendNotifyBO);
        }
        SendStatus sendStockStatus = sendOrderToPurchaseNotifyToShopTemplate.syncSend(RocketMqConstant.SEND_ORDER_TO_PURCHASE_NOTIFY_TO_SHOP_TOPIC, new GenericMessage<>(notifyList)).getSendStatus();
        if (!Objects.equals(sendStockStatus, SendStatus.SEND_OK)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
    }
}
